const express = require('express')
const isEqual = require('./until/equalObj.js')
const rander = require('./until/randerNumber.js')
const deepClone = require('./until/deepClone.js')
const router = express.Router()
// 下载multiparty 插件 用来传送图片
const multiparty = require("multiparty")
// 下载uuid npm install uuid --save 用来生成唯一名字
// 下载images插件 用来做24行的（图片处理）
const images = require("images")
const uuid = require('uuid')
//解析post请求中对象格式中间件
router.use(express.json())
//解析post请求urlencoded格式中间件
router.use(express.urlencoded())
//开放图片接口
router.get('/img/*',(req,res)=>{
  res.sendFile(__dirname+"/public"+req.url)
})
//静态数据
const imgs = ['vwo7','uwv6','7364','x5tb']

const userData = [
  {
    key: '1',
    avatar:"http://localhost:3000/api/img/264fc100-9315-11ec-ab09-9b3b081b3612.png",
    name: 'Serati Ma',
    password:'123456',
    username: '15170718283',
    email:'2338973980@qq.com',
    location:['360000', '360400', '360482'],
    locationName:['江西省','九江市','共青城市'],
    individualResume:'目标越接近，困难越增加。但愿每一个人都像星星一样安详而从容地不断沿着既定的目标走完自己的路程。——歌德'
  },
  {
    key: '2',
    avatar:"http://localhost:3000/api/img/2e869150-9315-11ec-ab09-9b3b081b3612.png",
    name: '小李',
    password:'123456',
    username: '15188988857',
    email:'1234567@qq.com',
    location:["360000","360700","360731"],
    locationName:['江西省','赣州市','于都县'],
    individualResume:'人生若只如初见，何事秋风悲画扇。  ———纳兰嫣德'
  },
  {
    key: '3',
    avatar:"http://localhost:3000/api/img/b37e6350-9d4d-11ec-b7a7-8fc94c545729.png",
    name: '小美',
    password:'123456',
    username: '13033214654',
    email:'18720276603@qq.com',
    location:["360000","360700","360731"],
    locationName:['江西省','赣州市','于都县'],
    individualResume:'天生我才必有用，千金散尽还复来。  ———李白'
  },
]
const user_role=[
  {
    user_key:'1',
    role_key:['11']
  },
  {
    user_key:'2',
    role_key:['22']
  },
  {
    user_key:'3',
    role_key:['33']
  }

]
const roleData = [
  {
    key: '11',
    del:0,
    name: '超级管理员',
    des:'开发人员',
    status: 1,
    submitTime:'2022-02-21 14:00:37',
    code:''
  },
  {
    key: '22',
    del:0,
    name: '管理员',
    des:'商铺管理员',
    status: 1,
    submitTime:'2022-02-21 14:20:37',
    code:''
  },
  {
    key: '33',
    del:0,
    name: '普通用户',
    des:'客户',
    status: 1,
    submitTime:'2022-02-21 14:30:37',
    code:''
  },
]
const role_power=[
  {
    role_key:'11',
    power_key:['111','222','333','444','555','666','777','888','999','000']
  },
  {
    role_key:'22',
    power_key:['444','555','777','888','999','000']
  },
  {
    role_key:'33',
    power_key:['111','888','999','000']
  }
]
const powerData = [
  {
    key: '111',
    del:0,
    powerType:'menu',
    des:'用户管理',
    status: 1,
    url:'/home/user_mgr',
    code:'account_mgr'
  },
  {
    key: '222',
    del:0,
    powerType:'menu',
    des:'角色管理',
    status: 1,
    url:'/home/role_mgr',
    code:'account_mgr'
  },
  {
    key: '333',
    del:0,
    powerType:'menu',
    des:'权限管理',
    status: 1,
    url:'/home/per_mgr',
    code:'account_mgr'
  },
  {
    key: '444',
    del:0,
    powerType:'menu',
    des:'商品管理',
    status: 1,
    url:'/home/goods_mgr',
    code:'shops_mgr'
  },
  {
    key: '555',
    del:0,
    powerType:'menu',
    des:'订单管理',
    status: 1,
    url:'/home/order_mgr',
    code:'shops_mgr'
  },
  {
    key: '666',
    del:0,
    powerType:'menu',
    des:'账号管理',
    status: 1,
    url:'account_mgr',
    code:'0',
    sort:'0'
  },
  {
    key: '777',
    del:0,
    powerType:'menu',
    des:'商铺管理',
    status: 1,
    url:'shops_mgr',
    code:'0',
    sort:'1'
  },
  {
    key: '888',
    del:0,
    powerType:'menu',
    des:'商品统计',
    status: 1,
    url:'/home/goods_count',
    code:'sell_count'
  },
  {
    key: '999',
    del:0,
    powerType:'menu',
    des:'订单统计',
    status: 1,
    url:'/home/order_count',
    code:'sell_count'
  },
  {
    key: '000',
    del:0,
    powerType:'menu',
    des:'销售统计',
    status: 1,
    url:'sell_count',
    code:'0',
    sort:'2'
  },
]
const goodsData = [
  {
    key:'1111',
    name:'红烧鸡块饭',
    price:13.5,
    number:25,
    describe:'鸡腿肉,少量辣椒',
    avatar:'http://localhost:3000/api/img/a9419720-9dcc-11ec-8384-a79a37153be1.jpg'
  },
  {
    key:'2222',
    name:'啤酒鸭盖浇饭',
    price:12.98,
    number:27,
    describe:'鸭,大蒜,啤酒',
    avatar:'http://localhost:3000/api/img/a4df7580-9dcc-11ec-8384-a79a37153be1.jpg'
  },
  {
    key:'3333',
    name:'青岛啤酒',
    price:4,
    number:15,
    describe:'学生慎点！',
    avatar:'http://localhost:3000/api/img/9fa395b0-9dcc-11ec-8384-a79a37153be1.jpg'
  },
  {
    key:'4444',
    name:'猪脚饭',
    price:15.23,
    number:27,
    describe:'热,荤,猪脚肉',
    avatar:'http://localhost:3000/api/img/42add990-9f81-11ec-9077-f3a15bf27eaa.jpg'
  },
    {
    key:'5555',
    name:'鸡腿',
    price:6,
    number:15,
    describe:'料酒中餐！',
    avatar:'http://localhost:3000/api/img/3d498a30-9f81-11ec-9077-f3a15bf27eaa.jpg'
  },
]
const orderData = [
  {
    key:'11111',
    user_key:'3',
    goods_key:'1111',
    status:-1,
    describe:'多加米饭',
    start_time:'2022-3-9 18:31'
  },
  {
    key:'22222',
    user_key:'3',
    goods_key:'2222',
    status:0,
    describe:'不要辣椒',
    start_time:'2022-3-9 17:31'
  },
  {
    key:'33333',
    user_key:'2',
    goods_key:'3333',
    status:0,
    describe:'要冰',
    start_time:'2022-3-9 11:31'
  },
  {
    key:'44444',
    user_key:'1',
    goods_key:'1111',
    status:1,
    describe:'无',
    start_time:'2022-3-7 11:31'
  },
]
//订单管理相关接口
router.get('/order',(req,res)=>{
  let orderData1=deepClone(orderData)
  orderData1.map((item)=>{
    userData.map((item1)=>{
      if(item.user_key===item1.key){
        item.user_key=item1.name
      }
    })
    goodsData.map((item2)=>{
      if(item.goods_key===item2.key){
        item.goods_key=item2.name
      }
    })
  })
  res.send(orderData1)
})

// router.post('/orderAdd',(req,res)=>{
//   const body = req.body
//   orderData.unshift(body)
//   res.send(body)
// })

router.post('/deleteOrder',(req,res)=>{
  const body = req.body
  let index = []
  orderData.map((val,i)=>{
    body.map((val1,j)=>{
      if(val.key===val1){
        index.push(i)
      }
    })
  })
  for(let i=index.length-1 ;i>=0;i--){
    orderData.splice(index[i],1)
  }
  res.send(body)
})

router.post('/updateOrder',(req,res)=>{
  const body = req.body
  orderData.map((val,i)=>{
      if(val.key===body.key){
        val.status = body.status
      }
  })
  res.send(orderData)
})

router.get('/searchorder',(req,res)=>{
  let {value}=req.query
  let orderData1=deepClone(orderData)
  orderData1.map((item)=>{
    userData.map((item1)=>{
      if(item.user_key===item1.key){
        item.user_key=item1.name
      }
    })
    goodsData.map((item2)=>{
      if(item.goods_key===item2.key){
        item.goods_key=item2.name
      }
    })
  })
  let orderSearch= orderData1.filter((ele)=>{
    return ele.key.match(value)
  })
  res.send(orderSearch)
})
//商品管理相关接口
router.get('/goods',(req,res)=>{
  res.send(goodsData)
})

router.post('/goodsAdd',(req,res)=>{
  const body = req.body
  goodsData.unshift(body)
  res.send(body)
})

router.post('/deleteGoods',(req,res)=>{
  const body = req.body
  let index = []
  goodsData.map((val,i)=>{
    body.map((val1,j)=>{
      if(val.key===val1){
        index.push(i)
      }
    })
  })
  for(let i=index.length-1 ;i>=0;i--){
    goodsData.splice(index[i],1)
  }
  res.send(body)
})

router.post('/updateGoods',(req,res)=>{
  const body = req.body
  goodsData.map((val,i)=>{
      if(val.key===body.key){
        goodsData.splice(i,1,body)
      }
  })
  res.send(goodsData)
})

router.get('/searchGoods',(req,res)=>{
  let {value}=req.query
  let goodsSearch= goodsData.filter((ele)=>{
    return ele.name.match(value)||ele.describe.match(value)
  })
  res.send(goodsSearch)
})
//获取当前用户所有权限
router.get('/getUserPer',(req,res)=>{
  const {key}=req.query
  let role_key=[]
  user_role.map((item)=>{
    if(item.user_key===key){
      role_key=item.role_key
    }
  })
  let power_key=[]
  role_power.map((item)=>{
    if(item.role_key===role_key[0])
    {
      power_key=item.power_key
    }
  })
  let powerAll=[]
  powerData.map((item)=>{
    let flag=false
    power_key.map((item1)=>{
      if(item.key===item1){
        flag=true
      }
    })
    if(flag===true){
      powerAll.push(item)
    }
  })
  res.send(powerAll)
})
//角色和权限关系接口
router.get('/role_power',(req,res)=>{
  const {data}=req.query
  let power=[]
  role_power.map((item,index)=>{
    if(item.role_key===data){
      item.power_key.map((item1,index1)=>{
        powerData.map((item2,index2)=>{
          if(item1===item2.key){
            power.unshift(item2)
          }
        })
      })
    }
  })
  res.send(power)
})
router.post('/role_power',(req,res)=>{
  const body = req.body
  role_power.map((item)=>{
    if(item.role_key===body.role_key){
      item.power_key = body.power_key
    }
  })
  res.send()
})
//用户和角色关系接口
router.get('/user_role',(req,res)=>{
  const {data}=req.query
  let role=[]
  user_role.map((item,index)=>{
    if(item.user_key===data){
      item.role_key.map((item1,index1)=>{
        roleData.map((item2,index2)=>{
          if(item1===item2.key){
            role.unshift(item2)
          }
        })
      })
    }
  })
  res.send(role)
})
router.post('/user_role',(req,res)=>{
  const body = req.body
  user_role.map((item)=>{
    if(item.user_key===body.user_key){
      item.role_key = body.role_key
    }
  })
  res.send()
})
//用户登入验证接口
router.post('/userLogin',(req,res)=>{
  const body = req.body
  let flag=false
  let token
  userData.map((item)=>{
    if(isEqual({username:item.username,password:item.password},body))
    {
      flag=true
      token=item.key
    }
  })
  if(flag){
    res.send({
      username:body.username,
      token:token
    })
  }
  else{
    res.send()
  }
})
router.get('/getcode',(req,res)=>{
  let code = {code:imgs[rander(0,3)]}
  res.send(code)
})


//和用户相关的接口
router.get('/searchUser',(req,res)=>{
  let {value}=req.query
  let userSearch= userData.filter((ele)=>{
    return ele.name.match(value)|| ele.email.match(value) ||ele.username.match(value)
  })
  res.send(userSearch)
})

router.get('/user',(req,res)=>{
  res.send(userData)
})
router.get('/userOne',(req,res)=>{
  let {key}=req.query
  let userOne
  userData.map((item)=>{
    if(item.key===key){
      userOne = {...item}
    }
  })
  res.send(userOne)
})
router.post('/userAdd',(req,res)=>{
  const body = req.body
  userData.unshift(body)
  user_role.unshift({user_key:body.key,role_key:[]})
  res.send(body)
})
router.post('/deleteUser',(req,res)=>{
  const body = req.body
  let index = []
  userData.map((val,i)=>{
    body.map((val1,j)=>{
      if(val.key===val1){
        index.push(i)
      }
    })
  })
  for(let i=index.length-1 ;i>=0;i--){
    userData.splice(index[i],1)
  }
  res.send(body)
})
router.post('/updateUser',(req,res)=>{
  const body = req.body
  userData.map((val,i)=>{
      if(val.key===body.key){
        userData.splice(i,1,body)
      }
  })
  res.send(userData)
})
//上传图片接口
router.post('/upload', function(req, res, next) {
  let form = new multiparty.Form()
  form.parse(req, function(err, fields, files) {
    // //找到上传的图片上传之前的名字
    let orgFilename = files.file[0].originalFilename;
    // //切割orgFilename 找到图片的扩展名 以证明图片是什么格式的
    // //切割后是一个数组，找到数组最后一个
    let formate = orgFilename.split(".");
    // //拼接新的图片名称
    let fileName = uuid.v1() + "." + formate[formate.length - 1];
    //  将图片存储到服务器本地
    images(files.file[0].path) //Load image from file 
    .size(1000, 1000) // 这里一定要先把这个public/images文件夹给创建好 不然要报错哦
    .save("public/img/" + fileName, {
      quality: 1000
    })
    //返回前台存储地址
    let src = "/api/img/" + fileName;
    res.json({
    status: true,
    img: src
    })
  })
})

//和角色相关的接口
router.get('/role',(req,res)=>{
  res.send(roleData)
})

router.post('/roleAdd',(req,res)=>{
  const body = req.body
  roleData.unshift(body)
  role_power.unshift({role_key:body.key,power_key:[]})
  res.send(body)
})

router.post('/deleteRole',(req,res)=>{
  const body = req.body
  let index = []
  roleData.map((val,i)=>{
    body.map((val1,j)=>{
      if(val.key===val1){
        index.push(i)
      }
    })
  })
  for(let i=index.length-1 ;i>=0;i--){
    user_role.map((item)=>{
      item.role_key=item.role_key.filter(item1=>item1!==roleData[index[i].key])
    })
    role_power.splice(index[i],1)
    roleData.splice(index[i],1)
  }
  res.send(body)
})

router.post('/updateRole',(req,res)=>{
  const body = req.body
  roleData.map((val,i)=>{
      if(val.key===body.key){
        roleData.splice(i,1,body)
      }
  })
  res.send(roleData)
})

router.get('/searchRole',(req,res)=>{
  let {value}=req.query
  let roleSearch= roleData.filter((ele)=>{
    return ele.name.match(value)
  })
  res.send(roleSearch)
})

router.get('/allRole',(req,res)=>{
  res.send(roleData)
})


//和权限相关的接口
router.get('/power',(req,res)=>{
  res.send(powerData)
})

router.post('/powerAdd',(req,res)=>{
  const body = req.body
  powerData.unshift(body)
  res.send(body)
})

router.post('/deletePower',(req,res)=>{
  const body = req.body
  let index = []
  powerData.map((val,i)=>{
    body.map((val1,j)=>{
      if(val.key===val1){
        index.push(i)
      }
    })
  })
  for(let i=index.length-1 ;i>=0;i--){
    role_power.map((item)=>{
      item.power_key=item.power_key.filter(item1=>item1!==powerData[index[i].key])
    })
    powerData.splice(index[i],1)
  }
  res.send(body)
})

router.post('/updatePower',(req,res)=>{
  const body = req.body
  powerData.map((val,i)=>{
      if(val.key===body.key){
        powerData.splice(i,1,body)
      }
  })
  res.send(powerData)
})

router.get('/searchPower',(req,res)=>{
  let {value}=req.query
  let powerSearch= powerData.filter((ele)=>{
    return ele.des.match(value)||ele.powerType.match(value)||ele.url.match(value)||ele.code.match(value)
  })
  res.send(powerSearch)
})
router.get('/allPower',(req,res)=>{
  res.send(powerData)
})


//测试接口
router.get('/get',(req,res)=>{
  const query = req.query
    console.log(res)
  res.send({
    status:1,
    msg:'get请求成功！',
    data:query
  })
})

router.post('/post',(req,res)=>{
  const body = req.body
  res.send({
    status:0,
    msg:'post请求成功！',
    data:body
  })
})
// router.get('/',(req,res)=>{
//   res.render('index.html')
// })
module.exports = router